"""
计算一个文件夹中所有TIFF图像的平均值/总值栅格
需要所有的TIFF图像空间参考、地理转换参数一致
"""

from osgeo import gdal,osr
import numpy as np
import os


year=2002
input_folder=rf"D:\Lenovo\Desktop\云南大学\毕业设计\毕设数据\原始数据\生物质燃烧面积\GFED4s\2001_tiff"
tiff_avg_file=rf"D:\Lenovo\Desktop\云南大学\毕业设计\毕设数据\原始数据\生物质燃烧面积\GFED4s\2001_tiff\burned_fraction_2001_sum.tif"


arr_mean=None
i=0
for file in os.listdir(input_folder):
    if file.endswith(".tif"):
        tiff_path=os.path.join(input_folder,file)
        dataset=gdal.Open(tiff_path)
        band=dataset.GetRasterBand(1)
        arr=band.ReadAsArray()
        if arr_mean is None:
            arr_mean=np.zeros_like(arr,float)
        arr_mean+=arr
        i+=1
        geotransform=dataset.GetGeoTransform()
        projection=dataset.GetProjection()

# arr_mean=arr_mean/i   #若需计算平均值，则除以i，计算总值时注释此语句

print(arr_mean.shape)
print(geotransform)
print(projection)
nrows,ncols=arr_mean.shape

driver=gdal.GetDriverByName("GTiff")
output_dataset=driver.Create(tiff_avg_file,ncols,nrows,1,gdal.GDT_Float32)
output_dataset.SetGeoTransform(geotransform)
output_dataset.SetProjection(projection)

output_band=output_dataset.GetRasterBand(1)
output_band.WriteArray(arr_mean)
output_band.FlushCache()

output_band=None
print("Saved mean tiff file")



